package com.david.controller.api;

import com.david.annotation.CurrentAdmin;
import com.david.entity.AdminInfo;
import com.david.model.api.Response;
import com.david.service.AdminInfoService;
import com.google.common.collect.ImmutableBiMap;
import com.google.common.collect.ImmutableMap;
import com.mysql.jdbc.Constants;
import com.mysql.jdbc.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

@RequestMapping("/api")
@RestController
public class CommonController {

    @Autowired
    AdminInfoService adminInfoService;

    @Value("${fileLocation}")
    private String location;

    @GetMapping("getAdminInfo")
    @ApiOperation(value = "获取管理员信息", notes = "通过id获取管理员信息 权限等", tags = "admin")
    public Response<Map> getAdminInfo(@CurrentAdmin AdminInfo adminInfo) {
        Response<Map> result = new Response<>();
        AdminInfo admin = adminInfoService.GetAdminById(adminInfo.id);
        if (admin != null) {
            ArrayList<String> roles = new ArrayList<>();
            switch (admin.userRole) {
                case 10: //admin
                    roles.add("admin");
                    break;
                case 99: //system
                    roles.add("admin");
                    roles.add("system");
                default:
                    break;
            }

            result.data = ImmutableMap.of("userName", admin.getUserName(), "userId", admin.getId(), "roles", Arrays.asList("admin"));
        }
        return result;
    }

    @PostMapping("uploadImg")
    @ApiOperation(value = "上传图片", notes = "上传图片", tags = "imgs")
    public Response<Map> uploadImg(MultipartFile multipartFile) {
        Response<Map> result = new Response<>();

        if (multipartFile.isEmpty() || StringUtils.isNullOrEmpty(multipartFile.getOriginalFilename())) {
            result.data = ImmutableBiMap.of("result", false, "errMsg", "请选择上传文件！");
            return result;
        }

        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            result.data = ImmutableBiMap.of("result", false, "errMsg", "上传文件格式错误！");
            return result;
        }

        String fileOriginName = multipartFile.getOriginalFilename();
        String suffix  = fileOriginName.substring(fileOriginName.lastIndexOf(".")+1);
        //处理图片
        String filePath = location +"/images/";
        String file_name = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSS");
            String formDate = sdf.format(date);

            String fileName = formDate + "." + suffix;

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath + File.separator + fileName));
            byte[] bs = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
            bos.flush();
            bos.close();
            file_name = fileName;

            result.data = ImmutableBiMap.of("result", true, "file_name", "/uploads/" + file_name);
            return result;


        } catch (Exception e) {
            result.data = ImmutableBiMap.of("result", false, "errMsg", "上传失败，请稍后再试！");
            return result;
        }
    }

    @PostMapping("uploadFile")
    @ApiOperation(value = "上传文件", notes = "上传文件", tags = "files")
    public Response<Map> uploadFile(MultipartFile multipartFile) {
        Response<Map> result = new Response<>();

        if (multipartFile.isEmpty() || StringUtils.isNullOrEmpty(multipartFile.getOriginalFilename())) {
            result.data = ImmutableBiMap.of("result", false, "errMsg", "请选择上传文件！");
            return result;
        }

        String fileOriginName = multipartFile.getOriginalFilename();
        String suffix  = fileOriginName.substring(fileOriginName.lastIndexOf(".")+1);
        String contentType = multipartFile.getContentType();
        if (!contentType.contains("")) {
            result.data = ImmutableBiMap.of("result", false, "errMsg", "上传文件格式错误！");
            return result;
        }

        //处理图片
        String filePath = location + "/files/";
        String file_name = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            FileInputStream fileInputStream = (FileInputStream) multipartFile.getInputStream();
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSS");
            String formDate = sdf.format(date);

            String fileName = formDate + "." + suffix;

            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath + File.separator + fileName));
            byte[] bs = new byte[1024];
            int len;
            while ((len = fileInputStream.read(bs)) != -1) {
                bos.write(bs, 0, len);
            }
            bos.flush();
            bos.close();
            file_name = fileName;

            result.data = ImmutableBiMap.of("result", true, "file_name", "/uploads/" + file_name);
            return result;


        } catch (Exception e) {
            result.data = ImmutableBiMap.of("result", false, "errMsg", "上传失败，请稍后再试！");
            return result;
        }
    }


}
